package com.common.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.common.upload.FileInfo;
import com.common.upload.FileUpload;

public class FileUploadServlet extends HttpServlet {
	private HttpServletRequest req;
	private HttpServletResponse res;
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String method=req.getParameter("method");
		this.req=req;
		this.res=res;
		if("upload".equals(method)){
			upload();
		}else{
			downFile();
		}
	}
	private void upload() throws ServletException, IOException{
		FileUpload fileUpload = new FileUpload();
		
		FileInfo fileInfo = fileUpload.upload(req, res, "/upload");
		/*if("1".equals(fileInfo.getStatus())){
			req.setAttribute("flag", "1");
		}else{
			req.setAttribute("flag", "0");
		}
		req.setAttribute("fileInfo",fileInfo);
		req.getRequestDispatcher("../uploadFile.jsp").forward(req, res);*/
		JSONObject jsonObject = JSONObject.fromObject(fileInfo);
		res.setContentType("text/html; charset=utf-8");//  
		System.out.println("jsonObject==="+jsonObject);
		//res.getWriter().write(jsonObject);
		//res.getWriter().write(fileInfo.getFileUrl());
		jsonObject.write(res.getWriter());
	}
	private void downFile() throws IOException{
		String filePath=req.getParameter("filePath");
		String fileNameCn=req.getParameter("");
		OutputStream output = res.getOutputStream();
		byte b[] = new byte[1024];
		
		File fileLoad = new File(filePath);
		
		String docName = fileNameCn+".doc";
		docName = java.net.URLEncoder.encode(docName, "UTF-8");

		res.setHeader("Content-Disposition","attachment;filename="+ new String(docName.getBytes("UTF-8"), "GBK"));
		res.setContentType("application/doc;charset=gb2312");  //doc,ms-excel,pdf

		long fileLength = fileLoad.length();
		String length = String.valueOf(fileLength);

		res.setHeader("Content_Length", length);

		FileInputStream input = new FileInputStream(fileLoad);
		int n = 0;
		while ((n = input.read(b)) != -1) {
			output.write(b, 0, n);
		}
	}
}
